package cn.ucox.web.ms.components.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.PooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据交换平台FTP客户端
 *
 * @author chenw
 * @create 2017-06-09 13:46
 * @email javacspring@gmail.com
 */
public class DexFtpClient {

    private static final Logger logger = LoggerFactory.getLogger(FTPClient.class);

    private FTPClientPool ftpClientPool;

    public DexFtpClient(FtpConfig ftpConfig) {
        if (null == ftpConfig)
            throw new RuntimeException("ftp configuration is null");
        try {
            ftpClientPool = new FTPClientPool(ftpConfig);
        } catch (Exception e) {
            logger.error("init ftp pool error", e);
        }
    }

    public PooledObject<FTPClient> get() {
        int retryCount = 0;
        while (true) {
            if (retryCount > 3)
                break;
            try {
                PooledObject<FTPClient> client = ftpClientPool.borrowObject();
                if (null == client) {
                    try {
                        Thread.sleep(5000);
                        retryCount++;
                        continue;
                    } catch (InterruptedException e1) {
                        logger.error("ftp连接失败，等待5000ms重试", e1);
                    }
                }
                return client;
            } catch (Exception e) {
                logger.error("ftp连接失败，等待5000ms重试", e);
                try {
                    Thread.sleep(5000);
                    retryCount++;
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }

    public void close(PooledObject<FTPClient> pooledObject) {
        if (null != pooledObject) {
            try {
                ftpClientPool.returnObject(pooledObject);
            } catch (Exception e) {
                logger.error("release ftp connection error", e);
            }
        }
    }

    public void release(PooledObject<FTPClient> pooledObject) {
        if (null != pooledObject) {
            try {
                pooledObject.getObject().completePendingCommand();
                ftpClientPool.returnObject(pooledObject);
            } catch (Exception e) {
                logger.error("release ftp connection error", e);
            }
        }
    }
}
